<template>
  <div class="container">
    <el-row class="">
      <el-col :span="16" align="left">
        <el-input v-model="data.params.projectName" placeholder="项目名称" style="width: 120px; margin-right: 15px" />

        <SelectOption :options="data.statusList" :placeholder="'状态'" @change-value="changeValue"> </SelectOption>

        <el-button @click="search()" class="ordinary">搜索</el-button>
      </el-col>
      <el-col :span="8" align="right">

<!--        <el-button class="ordinary" @click="getExport()" v-limit="'XMZX:SZXMLXPS:LXSQ:EXPORT'">批量导出</el-button>-->
        <el-button class="ordinary" @click="handleExport()" v-limit="'XMZX:SZXMLXPS:LXSQ:EXPORT'"> 批量导出</el-button>
        <el-button type="danger" @click="handleDetect()" v-limit="'XMZX:SZXMLXPS:LXSQ:DELETE'">批量删除</el-button>
        <el-button type="primary" @click="handleAdd()" v-limit="'XMZX:SZXMLXPS:LXSQ:PROAPP'">立项申请</el-button>
        <el-button type="success" @click="submitTo()" v-limit="'XMZX:SZXMLXPS:LXSQ:SUBMIT'">提交</el-button>
      </el-col>
    </el-row>

    <div>
      <Table class="table_" :tableArr="data.allTableData" :pagination="data.page" :columns="data.columns"
        @delectTable="delectIds" @delectstatus="delectstatus" :total="data.page.total"    @row-click="handleRowClick" >
        <template #operate="{ row }">
          <el-button size="small" class="ordinary" v-if="row.status == '待提交'" :disabled="row.isLock == 1"
            @click.stop="handleUpdate(row)" v-limit="'XMZX:SZXMLXPS:LXSQ:EDIT'">编辑</el-button>
<!--          <el-button size="small" type="primary" v-else :disabled="row.isLock == 1" @click="handleEdit(row)"
            v-limit="'XMZX:SZXMLXPS:LXSQ:DETAILS'">详情</el-button>  -->
          <el-button size="small" type="primary"   @click.stop="handleEdit(row)"
            >详情</el-button>
        </template>
      </Table>
      <div class="example-pagination-block">
        <el-pagination :current-page="data.params.current" :page-size="data.params.size"
          :page-sizes="[10, 20, 30, 40, 50, 100]" background layout="prev, pager, next ,total,sizes,jumper"
          :total="data.page.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <el-dialog v-model="data.dialogVisible" width="80%" :show-close="false" @closed="data.addFlag = 0">
      <template #title>
        <div class="my-header">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="基本信息" name="first">
              <Information ref="getAssociation" :disabledFlag="data.addFlag == 2 ? true : false" v-if="data.dialogVisible"
                @valueFlag="valueFlag"   :orgAllList="data.unitList"></Information>
            </el-tab-pane>
            <el-tab-pane label="项目经费预算" name="second">
              <!-- <Members :members="data.members" @dataChange="dataChange" @paramsChange="paramsChange"></Members> -->
              <Budget @tableJson="tableJson" :fatherTableJson="data.tableJson" :addFlag="data.addFlag" />
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">关闭</el-button>
          <el-button type="primary" @click="handleSave()" v-if="data.addFlag != 2">保存</el-button>
          <!-- <el-button type="success" @click="handleAdd()">提交</el-button> -->
        </span>
      </template>
    </el-dialog>
    <!-- 导出字段选择 -->
    <Export
        :detailList="data.detailList"
        :showing="data.exportDialog"
        @close="closeExport"
        @handle-filed="handleFiled"
    ></Export>
  </div>
</template>
<script lang="ts">
import * as proxy from "@/constants/proxy";
import request from "@/utils/request";
import { getDictionaryList, } from '@/views/science/api/common';
import {ElMessage, ElMessageBox} from 'element-plus';
import { computed, reactive, ref } from 'vue';
import { useStore } from 'vuex';
import {
  deleteLxsqTeam,
  getAddApply,
  getInnovativeTalentTeamConfirm,
  getLxsqDetail,
  getLxsqList,
  getLxsqTeam,
  getLxsqTeam1,
  submitToDo,
  updatepupAddApply
} from '../../api/szhlxsp';
import Members from '../components/members/members.vue';
import platformFiles from '../components/platformFiles/platformFiles.vue';
import record from '../components/record/record.vue';
import SelectOption from '../components/selectOption/index.vue';
import Table from '../components/table/table.vue';
import { Modals, tips } from '../components/tips/tips';
import Information from '../lxsq/information.vue';
import Budget from './budgetTable.vue';
import tableData from './tableHeader.json';
import Export from '@/views/project/components/Export/index.vue'
import {getExportInnovativeTalentTeam1} from "@/views/science/api/digit";
export default {
  components: {
    SelectOption,
    Table,
    Information,
    Members,
    platformFiles,
    record,
    Budget,Export,
  },
  setup() {
    const store = useStore()
    const activeName = ref('first')
    let data = reactive({
      dialogVisible: false,
      addFlag: 0,
      recordShow: false,
      loading: false,
      page: { page: 1, limit: 10, total: 0 },
      params: {
        projectName: '',
        status: '',
        current: 1,
        size: 10,
      },
      selectedRows: [],
      columns: tableData.platformTableHeader,
      ids: [],
      status: [],
      allTableData: [],
      statusList: [],
      unitList: [],
      levelOptions: computed(() => store.state.innovativeTalents.cxlevelSelect),
      members: [],
      files: [],
      changeLogs: [],
      flag: null,

      baseInfo: [],
      memberList: [],
      fileList: [],
      updateId: '',//更新时的id
      tableJson: [],
      exportDialog: false,
      detailList: [] as any,
    });
    const closeExport = () => {
      data.exportDialog = false
    }
    const handleFiled = (arr) => {
      console.log(arr, 'handleFiled')
      // let sdt = selectArr.map((el) => el.id);
      if (arr.length > 0) {
        ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          // exportProjectList({ ...searchParams, ids: sdt.join(",") , headList: arr }, '科研项目数据表格')
          getLxsqTeam1({ ...data.params, ids: data.ids , headList: arr}, "数字化立项申请");
          console.log('批量导出')
          data.exportDialog = false;


        })
      }
    }
    const handleExport = () => {
      data.exportDialog = true
      data.detailList = [
        { fieldName: 'projectName', title: '项目名称' },
        { fieldName: 'projectCategory', title: '项目类别' },
        { fieldName: 'projectStartTime', title: '项目开始时间' },
        { fieldName: 'projectEndTime', title: '预计完成时间' },
        // { fieldName: 'projectLeader', title: '项目负责人' },
        { fieldName: 'applyUnit', title: '申报单位' },
        // { fieldName: 'projectLeader', title: '项目负责人' },
        // { fieldName: 'contactPhone', title: '联系电话' },
        // { fieldName: 'completionPeriod', title: '完成年限' },
        { fieldName: 'totalBudget', title: '总投资(万元)' },
        // { fieldName: 'applyBudget', title: '申请中咨拨款(万元)' },
        { fieldName: 'applyDate', title: '申报日期' },
        { fieldName: 'summarize', title: '概述' },
        { fieldName: 'demandAnalysis', title: '现状及需求分析' },
        { fieldName: 'feasibilityNalysis', title: '项目必要性和可行性分析' },
        { fieldName: 'implementationPlan', title: '项目内容和实施方案' },
        { fieldName: 'projectSchedule', title: '项目进度计划' },
        { fieldName: 'projectCostEstimation', title: '项目费用估算' },
        { fieldName: 'projectBenefitAnalysis', title: '项目效益分析' },
        { fieldName: 'riskCountermeasure', title: '风险及对策' },
        { fieldName: 'stu', title: '状态' },
       /*          { fieldName: 'researchContent', title: '主要研究内容' },
                { fieldName: 'economicIndicator', title: '主要技术经济指标' },
                { fieldName: 'intellectualProperty', title: '创新点及可能获得的成果和知识产权' },
                { fieldName: 'projectBackground', title: '立项背景(包括项目背景、项目概况、研究的必要性等)' },
                { fieldName: 'feasibilityAnalysis', title: '国内外研究概况及可行性分析' },
                { fieldName: 'technicalIndex', title: '项目研究的主要内容及技术指标' },
                { fieldName: 'technicalRoute', title: '项目研究的技术路线' },
                { fieldName: 'benefitForecast', title: '推广应用前景及经济效益预测' },
                { fieldName: 'unitDivision', title: '申报单位和协作单位及分工' },
                { fieldName: 'economicIndicator', title: '主要技术经济指标' },
                { fieldName: 'intellectualProperty', title: '创新点及可能获得的成果和知识产权' },*/
      ]
    }
    interface Config {
      id: string;
      status: string;
    }
    let selectArr: Config[] = reactive([]);
    const handleSelectionChange = (val) => {
      selectArr = val;
    };
    //分页操作
    const handleSizeChange = (val) => {
      data.params.current = 1
      data.params.size = val
      tableList()
    }

    const handleCurrentChange = (val) => {
      data.params.current = val
      tableList()
    }
    const value = ref('2021-10-29')
    const holidays = [
      '2021-10-01',
      '2021-10-02',
      '2021-10-03',
      '2021-10-04',
      '2021-10-05',
      '2021-10-06',
      '2021-10-07',
    ]

    const isHoliday = ({ dayjs }) => {
      return holidays.includes(dayjs.format('YYYY-MM-DD'))
    }

    //主页面表格初始化
    const tableList = async () => {
      let res = await getLxsqList(data.params)
      if (res.data.success) {
        let records = res.data.data
        records.records.forEach((item) => {

          switch (item.status) {
            case 0: item.status = '草稿'; break;
            case 1: item.status = '待提交'; break;
            case 2: item.status = '待专家评审'; break;
            case 3: item.status = '专家评审未通过'; break;
            case 4: item.status = '领导班子会审不通过'; break;
            case 5: item.status = '待领导班子会审'; break;
            case 6: item.status = '待批准'; break;
            case 7: item.status = '批准立项'; break;
            case 8: item.status = '立项拒绝'; break;
          }
        })

        data.allTableData = records.records
        data.page.total = records.total
      }
    }

    //详情数据获取
    const detailData = async (id) => {
      let res = await getLxsqDetail(id)
      if (res.data.success) {
        const config = { ...res.data.data.info };
        config.approvalFilePath = config.approvalFilePath ? JSON.parse(config.approvalFilePath) : [];
        store.commit('lxsq/lxsqInfo', config)
        data.tableJson = res.data.data.contractBudgetList
        console.log('fatcher', config);

        // data.members = res.data.data.members
        // data.files = res.data.data.files
        // data.changeLogs = res.data.data.changeLogs
      }
    }

    const changeValue = (item) => {
      data.params.status = item.itemValue
    }


    const delectIds = (ids) => {
      data.ids = ids
    }

    const delectstatus = (status) => {
      data.status = status
    }

    const valueFlag = (flag) => {
      data.flag = flag
    }

    const paramsChange = (params) => {
      data.memberList = params
    }

    const filesParams = (params) => {
      data.fileList = params
    }
    //详情投资金额变动
    const tableJson = (val) => {
      data.tableJson = val.contractBudgetList
    }
    //提交
    const submitTo = () => {
      console.log("提交",data.status);
      let panduan =0
      data.status.map((item) => {
        console.log(item);
        if(item != "待提交"){
          panduan = 1
        }
      });
      if(panduan == 1){
        ElMessage({
          message: '请选择待提交的项目',
          type: 'warning',
        })
        return;
      }
      Modals('是否提交数据', '提示', 'warning').then(async () => {
        if (data.ids.length > 0) {
          submitToDo({ id: data.ids.join(',') }).then(res => {
            if (res.data.code == 200) {
              ElMessage({
                message: '提交成功',
                type: 'success',
              })
              tableList()
            }
          })
        } else {
          ElMessage({
            message: '请选择要提交的项目',
            type: 'warning',
          })
        }
      }).catch(() => {
        console.log("点击了取消")
      })

    }
    //导出
    const getExport = async () => {
      Modals('是否导出全部数据', '提示', 'warning').then(async () => {
        await getLxsqTeam(data.params)
      }).catch(() => {
        console.log("点击了取消")
      })
    }

    const handleDetect = async () => {
      let panduan =0
      data.status.map((item) => {
        console.log(item);
        if(item != "待提交"){
          panduan = 1
        }
      });
      if(panduan == 1){
        ElMessage({
          message: '请选择待提交的项目',
          type: 'warning',
        })
        return;
      }

      if (data.ids.length) {
        Modals('是否删除选择内容', '提示', 'warning').then(async () => {
          let res = await deleteLxsqTeam(data.ids)
          if (res.data.success) {
            tips('删除成功', 'success')
            tableList()
          }
        }).catch(() => {
          console.log("点击了取消")
        })

      } else {
        tips('请选择', 'warning')
      }
    }

    const dataChange = () => {
      detailData(store.state.innovativeTalents.rowId)
    }

    // 点击查询按键，分页设置为当前页为1，
    const search = () => {
      data.page.page = 1
      console.log(data.params)
      tableList()
    }


    const getAssociation = ref()
    //打开申请弹窗--保存按钮
    const handleSave = async () => {
      const form = JSON.parse(JSON.stringify(store.state.lxsq.lxsqInfo));
      getAssociation.value.submitForm()
      if (!data.flag) {
        ElMessage({
          message: '请将基本信息补充完整',
          type: 'warning',
        })
        return
      }
      form.status = 1;
      form.approvalFilePath = form.approvalFilePath ? JSON.stringify(form.approvalFilePath) : "";
      const params = {
        info: form,
        contractBudgetList: data.tableJson,
      }
      let res
      if (data.addFlag == 0) {
        res = await getAddApply(params)
      } else if (data.addFlag == 1) {
        Reflect.set(params.info, 'id', data.updateId)
        res = await updatepupAddApply(params)
      }
      if (res.data.success) {
        console.log(res)
        data.dialogVisible = false
        activeName.value = 'first'
        tableList()
        ElMessage({
          message: '申请成功',
          type: 'success',
        })
      }
    }

    //打开申请弹窗 新增
    const handleAdd = () => {
      data.dialogVisible = true
      store.commit('technicalNorms/emptyForm')
      data.tableJson = []
      store.commit('lxsq/emptylxsqInfo')
      // console.log('打开申请弹窗',store.state.lxsq.lxsqInfo);
      data.addFlag = 0
      // data.files = []
      // store.commit('lxsq/lxsqInfo')
    }
    //打开申请弹窗 更新
    const handleUpdate = async (row) => {
      await detailData(row.id)
      data.updateId = row.id
      data.dialogVisible = true
      data.addFlag = 1
    }
    const handleRowClick = (row) => {
      handleEdit2(row)
    }
    const handleEdit2 = async (row) => {
      await detailData(row.id)
      data.dialogVisible = true
      data.addFlag = 2
      store.commit('lxsq/getRowId', row.id)
    }
    const handleEdit = async (row) => {
      await detailData(row.id)
      data.dialogVisible = true
      data.addFlag = 2
      store.commit('lxsq/getRowId', row.id)
    }

    const handleConfirm = async (row) => {
      Modals('是否确认当前流程', '提示', 'warning').then(async () => {
        let res = await getInnovativeTalentTeamConfirm(row.id)
        if (res.data.success) {
          tableList()
        }
      }).catch(() => {
        console.log("点击了取消")
      })
    }
    const getDictionaryList1 = async () => {
      const rst = await getDictionaryList(["KHGL_XMZL_SZXMLXPS_STATUS"])
      data.statusList = rst.data.data.KHGL_XMZL_SZXMLXPS_STATUS
      // const rst = await getDictByCodeList(a)
    }

    const getUnit = async () => {
      return request({
                url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
                method: "get",
            }).then(res =>{
                data.unitList = res.data.data
            })
    }


    const handleCloseDialog = () => {
      data.dialogVisible = false;
      data.recordShow = false;
      activeName.value = 'first'
    }

    tableList()
    getDictionaryList1()
    getUnit()


    return {
      data,
      activeName,
      valueFlag,
      getAssociation,
      paramsChange,
      filesParams,

      changeValue,
      delectIds,
      delectstatus,
      getExport,
      handleDetect,
      handleAdd,
      handleUpdate,
      dataChange,
      handleCloseDialog,

      handleEdit,
      handleConfirm,
      search,
      handleSave,
      submitTo,
      tableJson,
      getDictionaryList1,
      handleSizeChange,
      handleCurrentChange,

      closeExport,
      handleFiled,
      handleExport,
      handleRowClick,
      handleEdit2,
    }
  },
}
</script>
<style lang="scss">
.table_ {
  .el-pagination {
    display: none;
  }
}
</style>
<style lang="scss" scoped>
.example-pagination-block {
  margin-top: 15px;
  text-align: center;
}

:deep(.el-pagination .btn-next .el-icon) {
  margin: 0 auto;
}

.container {
  background-color: white;
  padding: 20px;
}

:deep(.el-dialog__body) {
  display: none;
}

// .el-col {
//   line-height: 40px;
// }

.el-form-item {
  .el-input {
    width: 100px;
  }

  .el-select {
    width: 100px;
  }
}

/* .demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
} */
</style>
